package net.zjitc.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.Serializable;

/**
 * @author 赵静静
 * @date 2019/3/22 12:10
 */

/*保证json序列化的时候，如果字段为null的值，则不序列化*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServiceResponse<T> implements Serializable {
    private int status;
    private String message;
    private T data;

    /*定义私有的构造器，方便后面公有方法的调用，这样定义比较优雅、简明、通用*/
    private ServiceResponse(int status){
        this.status =status;
    }

    private ServiceResponse(int status,T data){
        this.status =status;
        this.data = data;
    }

    /*当传入status 和 字符串时，会调用此方法*/
    private ServiceResponse(int status,String message){
        this.status =status;
        this.message = message;
    }
    private ServiceResponse(int status,String message,T data){
        this.status =status;
        this.message = message;
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    /*使用此注解，当json序列化的时候，忽略此字段*/
    @JsonIgnore
    public boolean isSuccess(){
        return this.status == ResponseCode.SUCCESS.getCode();
    }


    public static <T> ServiceResponse<T> createBySuccess(){
        return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode());
    }

    public static <T> ServiceResponse<T> createBySuccessMessage(String msg){
        return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static <T> ServiceResponse<T> createBySuccess(T data){
        return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }

    public static <T> ServiceResponse<T> createBySuccess(String msg , T data){
        return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
    }

    public static <T> ServiceResponse<T> createByError(){
        return new ServiceResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }

    public static <T> ServiceResponse<T> createByErrorMessage(String errorMessage){
        return new ServiceResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);
    }
    public static <T> ServiceResponse<T> createByErrorCodeMessage(int errorCode ,String errorMessage){
        return new ServiceResponse<T>(errorCode,errorMessage);
    }
}
